<template>
	<view class="tea-home-app">
		<map
			class="maps"
			:latitude="latitude"
			:longitude="longitude"
			:markers="markers"
			:enable-satellite="checkedWeixin"
			:enable-building="true"
			scale="15"
		></map>
		<view class="page-body">
			<view class="search-part">
				<view class="search-option" style="height: 80upx; border-radius: 10upx; flex: 1">
					<image
						src="../../../static/search-icon.png"
						style="width: 48upx; margin-left: 20upx"
						mode="aspectFit"
					/>
					<input
						@input="searchByName"
						class="keyword-input"
						v-model="searchOption.keyword"
						style="flex: 1; font-size: 32upx"
						placeholder="搜索门店"
					/>
					<text style="margin-right: 20upx; font-size: 32upx" @click="searchByName(keyword)">搜索</text>
				</view>
			</view>
			<!-- <view style="padding: 20upx 10upx 0 10upx;text-align: center;display: none">
						</view>
						<div class="page-section-spacing">
							<swiper class="swiper" indicator-dots="true" autoplay="true" interval="5000" duration="1500" circular>
								<swiper-item v-for="(item , index) in homeSlide" :key="index">
									<image :src="item.img" v-if="index===0" @click="goPage('/pages/tea/v2/joinus')"></image>
									<image :src="item.img" v-if="index===1" @click="goPage('/pages/tea/v2/joinus')"></image>
								</swiper-item>
							</swiper>
						</div> -->

			<view class="tea-list" v-if="!isRent">
				<view class="item" v-if="item.show" v-for="(item, key) in listData.items" :key="key">
					<view class="icon">
						<image v-if="!item.images" src="../../../static/default_img.png" />
						<image
							v-if="item.images"
							:src="item.images"
							@click="homeSlidePreviewImage(item.images)"
						/>
						<view class="title-wrap">
							<view class="status-notopen" v-if="item.teaHouseState == 0">筹备中</view>
							<view class="status-open" v-if="item.teaHouseState == 1">营业中</view>
							<view class="status-try" v-if="item.teaHouseState == 2">试营业中</view>
						</view>
					</view>
					<view class="info" @click="goHourDetail(item)">
						<view class="name">{{ item.name }}</view>
						<view class="address">地址：{{ item.address }}</view>
						<view class="time">营业时间：00:00 - 24:00</view>
						<view class="buttn">
							<view class="distance">距我{{ item.distance }}km</view>
							<view class="btn-icon">
								<view class="btn-item" @click.stop="showMapInfo(item)">
									<image class="store-icon" src="/static/map-point.png"></image>
								</view>
								<view class="btn-item" @click.stop="callPhone(item)">
									<image class="store-icon" src="/static/service.png"></image>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<AnnouncementPopup
			:showPopup="showAnnouncement"
			:announcementPoints="announcementPoints"
			@confirm="handleConfirmReading"
		/>
	</view>
</template>

<script>
import util from '@/libs/util.js';
import globalConfig from '../../../config';
import Modal from '@/components/neil-modal/neil-modal.vue';
import myTimer from '@/components/my-timer.vue';
import AnnouncementPopup from '@/components/AnnouncementPopup.vue';

const baseHttp = globalConfig.API_HOST;

export default {
	data() {
		return {
			showAnnouncement: true, // 控制弹窗是否显示
			announcementPoints: [
				// 公告内容点
				'1.严禁未成年人进入场所;',
				'2.严禁黄.赌.毒打架斗殴等一切违法活动;',
				'3.使用人须自行对身体状况负责,注意个人安全;',
				'4.破坏或带走本场所提供的设备设施请照价赔偿;',
				'5.请自行保管好私人物品,如有遗失概不负责;'
			],
			mtCode: '',
			dealgroupId: '',
			isLogin: false,
			showMap: false,
			isTimerStart: false,
			tabItemValue: 0,
			baseHttp: baseHttp,
			isCancelSubmit: false,
			user: {
				userId: null,
				teaHouseName: null
			},
			qrcodeDailog: {
				show: false
			},
			qrcodeRoomDailog: {
				show: false
			},
			tabItems: [
				{
					value: 0,
					label: '地图'
				},
				{
					value: 1,
					label: '列表'
				}
			],
			qcCodeRoom: '',
			order: {
				orderNO: '',
				orderType: 0,
				payState: 0,
				predictMoney: 8000,
				remark: '租用包厢',
				rentMins: 4,
				roomId: 9,
				startTime: '2021-01-01 16:05:38',
				teaHouseId: 8,
				userId: 6,
				qcCode: '',
				qcCodeRoom: ''
			},

			homeSlide: [
				{
					img: '../../../static/index/banner.png'
				},
				{
					img: '../../../static/index/banner1.png'
				}
			],
			isShowNewUserAd: false,
			keyword: '搜索位置找附近茶室',
			orderList: [],
			openHouseDialog: {
				show: false
			},

			distanceArr: [],
			appMap: null,
			firstMap: {
				latitude: null,
				longitude: null
			},
			map: {
				latitude: '',
				longitude: '',
				covers: [
					/*
						{
						  id: 1,
						    latitude: 23.02882,
						    longitude: 113.14278,
						  title: '地点1',
						  width:50,
						  height:50,
						    iconPath: '../../../static/point.png'
						},{
						  id: 2,
						    latitude: 23.05980,
						    longitude: 113.16039,
						  title: '地点2',
						  width:50,
						  height:50,
						    iconPath: '../../../static/point.png'
						}*/
				]
			},
			isRent: false,
			listData: {
				items: []
			},
			searchOption: {
				keyword: ''
			},
			latitude: 23.043594, //纬度
			longitude: 113.160704, //经度
			markers: [
				// {
				// 	title: '123',
				// 	latitude: 23.043594,
				// 	longitude: 113.160704,
				// 	iconPath: '/static/btn_loc0.png'
				// },
				// {
				// 	title: '123',
				// 	latitude: 23.036344,
				// 	longitude: 113.160704,
				// 	iconPath: '/static/btn_loc0.png'
				// },
				// {
				// 	title: '123',
				// 	latitude: 23.03528,
				// 	longitude: 113.149565,
				// 	iconPath: '/static/btn_loc0.png'
				// },
				// {
				// 	title: '123',
				// 	latitude: 23.03794,
				// 	longitude: 113.138498,
				// 	iconPath: '/static/btn_loc0.png'
				// },
				// {
				// 	title: '123',
				// 	latitude: 23.049247,
				// 	longitude: 113.145684,
				// 	iconPath: '/static/btn_loc0.png'
				// }
			] //标记点数组
		};
	},
	onLoad(params) {
		wx.showShareMenu({
			withShareTicket: true,
			menus: ['shareAppMessage', 'shareTimeline']
		});
	},
	onReady() {
		this.appMap = uni.createMapContext('teaHouseMap', this);
		this.initMap();

		setInterval(() => {
			this.firstMap.latitude = null;
			console.log('clear');
		}, 60000);
	},
	onShow() {
		if (global.isLogin()) {
			this.isLogin = true;
		} else {
			this.isLogin = false;
		}
		this.showAnnouncement = true;
		this.getUserDetail();
	},
	components: {
		Modal,
		AnnouncementPopup,
		myTimer
	},
	computed: {},
	methods: {
		...util,
		goUserHome() {
			this.goPage('/pages/user/info/home');
		},
		scanItem() {
			uni.scanCode({
				success: (res) => {
					if (res.result) {
						this.item.mtCode = res.result;
						this.submit();
					} else {
						this.$Message.error('识别失败');
					}
				}
			});
		},
		handleConfirmReading() {
			this.showAnnouncement = false; // 用户点击“我已仔细阅读了”后隐藏弹窗
			// 这里可以添加其他逻辑，比如保存用户已阅读状态到本地存储或服务器
		},

		homeSlidePreviewImage(image) {
			let imgs = image.split(',').map((item) => {
				return item;
			});
			uni.previewImage({
				urls: imgs,
				current: 0
			});
		},
		goHourDetail(item) {
			console.log(item);
			if(item.teaHouseState==0){
				this.$Message.error('新店待营业，敬请期待');
			}else{
				this.goPage(
					'/pages/tea/v2/index?teaHouseId=' +
						item.teaHouseId +
						'&mtCode=' +
						this.mtCode +
						'&dealgroupId=' +
						this.dealgroupId
				);
			}
			
		},
		openHouseDoor(orderNo) {
			this.$api
				.post('/roomOrder/controlMachine', {
					machineType: 3,
					state: 1,
					orderNo: orderNo
				})
				.then((response) => {
					if (response.ret === 1) {
						this.$Message.success('操作成功');
					} else {
						this.$Message.error(response.msg);
					}
				});
		},
		openRoomDoor(orderNo) {
			this.$api
				.post('/roomOrder/controlMachine', {
					machineType: 0,
					orderNo: orderNo,
					state: 1
				})
				.then((response) => {
					if (response.ret === 1) {
						this.$Message.success('操作成功');
					} else {
						this.$Message.error(response.msg);
					}
				});
		},
		openHouse() {
			if (this.isLogin) {
				this.$api.post('/roomOrder/getRenting', {}).then((response) => {
					if (response.ret === 1 && response.data && response.data.length > 0) {
						this.orderList = response.data;
						this.openHouseDialog.show = true;
					} else {
						this.$Message.error('无订单或订单未开始');
					}
				});
			} else {
				this.goPage('/pages/user/auth/auth');
				return false;
			}
		},
		initMap() {
			console.log('map init');

			if (this.firstMap.latitude) {
				this.appMap.moveToLocation({
					longitude: this.firstMap.longitude,
					latitude: this.firstMap.latitude
				});
				this.getMapTeaHouse(this.firstMap.longitude, this.firstMap.latitude);
			} else {
				uni.getLocation({
					type: 'gcj02',
					success: (res) => {
						this.map.latitude = res.latitude;
						this.map.longitude = res.longitude;

						this.firstMap.latitude = res.latitude;
						this.firstMap.longitude = res.longitude;

						//保存到token
						uni.setStorageSync('firstMap_latitude', res.latitude);
						uni.setStorageSync('firstMap_longitude', res.longitude);

						/*
							this.appMap.moveToLocation({
							  longitude: res.longitude,
							  latitude: res.latitude
							});
							*/
						this.getMapTeaHouse(res.longitude, res.latitude);
					},
					fail: (res) => {
						console.log(res);
						this.getDataList();
					}
				});
			}
		},
		searchPosition() {
			uni.chooseLocation({
				success: (res) => {
					this.map.covers = [];
					this.keyword = res.name;

					this.map.latitude = res.latitude;
					this.map.longitude = res.longitude;

					this.appMap.moveToLocation({
						longitude: res.longitude,
						latitude: res.latitude
					});

					this.getMapTeaHouse(res.longitude, res.latitude);
					console.log('位置名称：' + res.name);
					console.log('详细地址：' + res.address);
					console.log('纬度：' + res.latitude);
					console.log('经度：' + res.longitude);
				}
			});
		},
		getUserDetail() {
			this.$api.post('/user/getInfo', {}).then((response) => {
				if (response.ret === 1) {
					this.user = response.data;
					this.searchOption.keyword = this.user.teaHouseName;
					//this.searchByName({target:{value:this.user.teaHouseName}});
					this.isLogin = true;
				} else {
					this.isLogin = false;
					//this.$Message.info(response.msg)
				}
			});
		},
		callPhone(teaHouse) {
			uni.makePhoneCall({
				phoneNumber: teaHouse.tel //仅为示例
			});
		},
		// showMapInfo(item) {
		// 	//console.log(item);
		// 	//console.log(item);
		// 	if (this.isLogin) {
		// 		this.goPage('/pages/tea/default/mapDetail?id=' + item.teaHouseId);
		// 	}

		// 	return false;
			
		// },
		showMapInfo(item) {
			console.log(item);
			//console.log(item);
			
			if (item.lat && item.lon) {
				//console.log(this.item.latitude)
				//console.log(this.item.longitude)
		
				uni.openLocation({
					latitude: item.lat,
					longitude: item.lon,
					name:item.name,
					address: item.address,
					success: function () {
						console.log('success');
					}
				});
			} else {
				this.$Message.error('当前点位没有设置坐标');
			}
		
			return true;
			if (this.isLogin) {
				this.goPage('/pages/tea/default/mapDetail?id=' + item.teaHouseId);
			}
		
			return false;
		},
		
		onMapTap(tapPosition) {
			//console.log(tapPosition);
			//tapPosition.detail.latitude
			this.map.covers = [];
			this.getMapTeaHouse(tapPosition.detail.longitude, tapPosition.detail.latitude);
		},
		showQrcodeDialog(field) {
			this[field].show = true;
			this.getQRImage();
		},
		getMapTeaHouse(lon, lat) {
			this.$api
				.post('/teaHouse/getNear', {
					lon: lon,
					lat: lat,
					radius: 50000000
				})
				.then((response) => {
					let minDistance = 0;
					this.map.covers = [];
					if (response.data) {
						response.data.items = this.setField(response.data, 'show', true);
						this.distanceArr = [];
						console.log(response.data,666);
						for (let i = 0; i < response.data.length; i++) {
							var item = response.data[i];
							let distance = this.getDistance(lat, lon, item.lat, item.lon);
							console.log(distance,777);
							item.distance = distance;
							this.listData.items.push(item);
						}
						console.log(this.listData.items,666);
						this.listData.items.sort(function (a, b) {
							if (a.distance < b.distance) {
								return -1;
							} else if (a.distance == b.distance) {
								return 0;
							} else {
								return 1;
							}
						});
						this.latitude = this.listData.items[0].lat;
						this.longitude = this.listData.items[0].lon;
						this.listData.items.forEach((eleme) => {
							let obj = {
								title: eleme.name,
								latitude: eleme.lat,
								longitude: eleme.lon,
								iconPath: '/static/btn_loc0.png',
								label: {
									content: eleme.name,
									color: '#ff0000',
									fontSize: 12,
									bgColor: '$uni-theme-color',
									borderRadius: 5,
									padding: 10,
									anchorX: -30,
									anchorY: -90
								}
							};
							this.markers.push(obj);
						});
					}
				});
		},
		markertap(event) {
			if (event.detail.markerId > 1) {
				this.goPage('/pages/tea/v2/houseDetail?teaHouseId=' + event.detail.markerId);
			}
		},
		tabClick(item) {
			this.tabItemValue = item.value;
			this.showMap = !this.showMap;
		},
		searchByName(event) {
			let name = event.target.value;
			if (name && name.length > 0) {
				for (let i = 0; i < this.listData.items.length; i++) {
					//console.log(this.listData.items[i]);
					let index = this.listData.items[i].name.indexOf(name);
					if (index != -1) {
						this.listData.items[i].show = true;
					} else {
						this.listData.items[i].show = false;
					}
					console.log(index);
					console.log(this.listData.items[i]);
				}
			} else {
				this.setField(this.listData.items, 'show', true);
			}
		},
		cancelOrder() {
			if (this.isCancelSubmit) {
				return false;
			}
			uni.showModal({
				title: '提示',
				content: '确定结束？',
				success: (res) => {
					if (res.confirm) {
						//提交请求中
						uni.showLoading({
							title: '提交请求中'
						});

						this._cancelOrder();
					} else if (res.cancel) {
						//console.log('用户点击取消');
					}
				}
			});
		},
		_cancelOrder() {
			this.isCancelSubmit = true;

			this.$api.post('/roomOrder/finishOrder', {}).then((response) => {
				if (response.ret === 1) {
					this.$Message.success('结束订单成功');
					this.checkIsRent();
					this.isCancelSubmit = false;
				} else {
					if (response.msg == '余额不足') {
						//this.$Message.error("what");
						//调用充值接口

						//判断是否会员
						if (response.data === null || response.data === undefined) {
							this.isCancelSubmit = false;
							this.$Message.error(response.msg);
							this.goPage('/pages/user/info/vip');
						} else {
							this.toPay(response.data);
						}
					} else {
						this.$Message.error(response.msg);
						this.isCancelSubmit = false;
					}
				}
			});
		},
		toPay(money) {
			wx.login({
				success: (res) => {
					if (res.code) {
						this.wxCode = res.code;

						this.$api
							.post('/weixin/recharge', {
								code: this.wxCode,
								money: money
							})
							.then((response) => {
								if (response.ret === 1) {
									//console.log(response);
									let json = '{' + response.data + '}';
									json = json.replace(/'/g, '"');
									json = JSON.parse(json);

									uni.requestPayment({
										provider: 'wxpay',
										timeStamp: json.timeStamp,
										nonceStr: json.nonceStr,
										package: json.package,
										signType: json.signType,
										paySign: json.paySign,
										success: (res) => {
											//this._cancelOrder();
											this.$Message.success('支付成功');
											/*
											uni.navigateBack({
											  delta: 1
											});
											*/
										},
										fail: function (err) {
											console.log('fail:' + JSON.stringify(err));
										}
									});
								} else {
									this.$Message.error(response.msg);
								}
								this.isCancelSubmit = false;
							});
					}
				}
			});
		},
		getOrderInfo() {
			//判断当前是否有使用中的订单
		},
		getQRImage() {
			this.$api
				.post('/roomOrder/getQRImage', {
					lockType: 0
				})
				.then((imageResponse) => {
					this.order.qcCode = imageResponse.data;
				});

			this.$api
				.post('/roomOrder/getQRImage', {
					lockType: 1
				})
				.then((imageResponse) => {
					this.$nextTick(() => {
						this.order.qcCodeRoom = imageResponse.data;
					});

					//console.log("what");
					//console.log(this.order.qcCodeRoom)
				});
		},
		checkIsRent() {
			this.$api.post('/roomOrder/getRenting', {}).then((response) => {
				if (response.ret === 1) {
					this.order = response.data;

					let startTime = new Date(this.order.startTime.replace(/-/g, '/')).getTime() / 1000;
					//var endTime = new Date(this.selectedTime.replace(/-/g,'/')).getTime()/1000;
					let currentTime = Date.parse(new Date()) / 1000;
					let useTime = currentTime - startTime;

					this.order.useTime = '00:00:00';

					if (this.isRent == false) {
						this.getQRImage();
					}
					this.isRent = true;

					this.$nextTick(() => {
						this.$refs.myTimer.setCurrentTime(useTime);
						if (this.isTimerStart == false) {
							this.isTimerStart = true;
							this.$refs.myTimer.start();
						}
					});
				} else {
					this.isRent = false;
				}
			});
		},
		getDataList() {
			uni.showLoading({
				title: '加载中'
			});
			this.$api
				.post('/teaHouse/queryPage', {
					pageNo: 1,
					dealgroupId: this.dealgroupId
				})
				.then((response) => {
					response.data.items = this.setField(response.data, 'show', true);
					this.listData.items = response.data;
					uni.hideLoading();
				});
		},
		goPage(url) {
			if (!this.isLogin) {
				uni.navigateTo({
					url: '/pages/user/auth/auth'
				});
			} else {
				//console.log(url);
				uni.navigateTo({
					url: url
				});
			}
		}
	}
};
</script>

<style lang="scss">
page {
	height: 100%;
}

.maps {
	width: 100%;
	height: 100vh;
	position: relative;
}
.page-body {
	width: 100%;
	position: absolute;
	top: 0;
	left: 0;
}
.tea-home-app {
	background-color: #f5f5f5;
}
// 搜索
.search-part {
	/*top:0;*/
	width: 100%;
	padding-top: 20upx;
	background-color: #f5f4f8;
	.search-option {
		background-color: white;
		margin: 0 20upx;
		color: #bbbbbb;
		display: flex;
		align-items: center;
	}
}

// 门店
.tea-list {
	height: 100%;
	margin-left: 18upx;
	margin-right: 18upx;
	.item {
		display: flex;
		padding: 28upx;
		margin-top: 20upx;
		background-color: white;
		.icon {
			width: 160upx;
			height: 160upx;
			margin-right: 20upx;
			position: relative;
			box-shadow: 0px 4px 8px 0px rgba(0, 0, 0, 0.1);
			image {
				width: 160upx;
				height: 160upx;
				border-radius: 10upx;
			}
			.title-wrap {
				position: absolute;
				top: 0;
				left: 0;
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding-bottom: 20rpx;

				.status-notopen {
					border-radius: 3px;
					font-size: 13px;
					padding: 3px 6px;
					background-color: #f00;
					color: #fff;
				}
				.status-try {
					border-radius: 3px;
					border: 1px solid #f0e6e6;
					font-size: 13px;
					padding: 3px 6px;
					background-color: #ecfbf3;
					color: #26bd9c;
				}
				.status-open {
					border-radius: 3px;
					font-size: 13px;
					padding: 3px 6px;
					background-color: $uni-theme-color;
					color: #fff;
				}
			}
		}

		.info {
			flex: 1;
			margin-left: 20upx;
			font-size: 32upx;
			display: flex;
			flex-direction: column;
			justify-content: space-between;

			.name {
				font-size: 28upx;
				color: #000000;
				font-weight: bold;
				white-space: nowrap;
				text-overflow: ellipsis;
				overflow: hidden;
			}
			.address {
				font-size: 24upx;
				color: #767676;
			}

			.time {
				font-size: 24upx;
				color: #767676;
			}
			.buttn {
				display: flex;
				justify-content: space-between;
				align-items: center;
				font-size: 24upx;
				.distance {
					font-size: 20upx;
					color: $uni-theme-color;
					padding: 4rpx 8rpx;
					border: 1px solid $uni-theme-color;
					text-align: center;
				}
				.btn-icon {
					display: flex;
				}
				.btn-item {
					flex: 1;
					width: 52rpx;
					height: 52rpx;
					background-color: $uni-theme-color;
					border-radius: 26rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					margin-left: 20rpx;
					.store-icon {
						width: 26rpx;
						height: 26rpx;
					}
				}
			}
		}
	}
}
// 轮播
.tea-home-app {
	background-color: #f5f3f3;
	//color:#707070;
	//height: 100%;

	.page-section-spacing {
		width: 100%;
		// margin: 50upx auto;
		margin: 20upx auto;
		// box-shadow: 0px 20px 20px -20px #1D2C6D;
		// box-shadow: 0px 20px 20px -20px $uni-theme-color;
	}

	.swiper {
		height: 400upx;
	}

	// swiper-item 里面的图片高度
	swiper-item image {
		width: 100%;
		height: 100%;
	}

	.search {
		width: 100%;
		padding: 20upx;
		background-color: white;
		display: flex;

		.image {
			width: 55upx;
			height: 40upx;
			margin-right: 10upx;
		}
	}
}
</style>
